var express = require('express');
var querystring = require('querystring');
var router = express.Router();
var data = require('./data');

/**
 * map读取，通过地图id读取任意地图
 */
router.get('/', function(req, res, next) {
    console.log(req.query);
    // console.log(JSON.parse(req.query.map));
    let acc = req.query.acc;
    let mapid = req.query.mapid;
    let mapdata;
    console.log(data.wholeMapData);
    if(acc)
    {
      for(let key in data.wholeMapData)
      {
        if(data.wholeMapData[key].ower == acc)
        {
          mapdata = data.wholeMapData[key];
        }
      }
    }
    else if(mapid)
    {
      mapdata = data.wholeMapData[mapid];
    }
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.send(JSON.stringify(mapdata));
});

/**
 * map主要提供地图数据上传
 */
router.post('/upload',function(req, res, next) {
    console.log(req.query);
    let acc = req.query.acc;
    var body = "";
    req.on('data', function (chunk) {
      body += chunk;  //一定要使用+=，如果body=chunk，因为请求favicon.ico，body会等于{}
      // console.log("chunk:",chunk);
    });
    req.on('end', function () {
      body = querystring.parse(body);
      console.log(body);
      let obj;
      for(let key in body)
      {
        obj = JSON.parse(key);
      }
      upload_map(acc,obj,res);
    });
});

/**
 * 购买道具，扣除玩家money
 */
router.post('/buy',function(req, res, next) {
  console.log(req.query);
  console.log(req.body);
});
//指定帐号上传地图数据
function upload_map(acc,map_data,res)
{
  let accData = data.wholeAccData[acc];
  let mapData;
  res.setHeader("Access-Control-Allow-Origin", "*");
  if(accData)
  {
    let id = data.getMapId();
    console.log("id:",id);
    accData.maps.push(id);
    mapData = new data.MapData(acc,map_data,null);
    data.wholeMapData[id.toString()] = mapData;
    res.send({"code":0,"mapid":id,"msg":"上传成功"});
  }
  else
  {
    res.send("没有帐号，地图上传失败");
  }
}


module.exports = router;
